/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 指定内容生成pdf工具类
 * 
 * @Title com.enfry.util.PdfUtil
 * @author Penghu
 * @date 2018年3月2日
 */
public class PdfUtil {

	static Logger log = LoggerFactory.getLogger(PdfUtil.class);

	private static String getHtml(String content, int width) {
		if (width <= 0) {
			width = 860;
		}
		String temp = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
		temp += "<style type=\"text/css\"><!-- table{margin: 0px;padding: 0px;min-width:" + 860
				+ "px;display:block;vertical-align:top;}//--></style>";
		temp += "</head><body><div style=\"width:" + width + "px;\">";
		temp += content;
		temp += "</div></body>";

		return temp;
	}

	/**
	 * 指定内容生成pdf格式
	 * 
	 * @param content 生成数据内容
	 * @param cmdPath 命令位置
	 * @param srcPath 生成html路径
	 * @param destPath 生成数据路径
	 * @param width 内容宽度
	 * @return
	 * @return boolean
	 * @throws
	 * @author Penghu
	 * @date 2018年3月2日
	 */
	public static boolean toPdf(String content, String cmdPath, String srcPath, String destPath,
			int width) {
		Process process = null;
		try {
			String html = getHtml(content, width);
			Files.writeUTF8(srcPath, html);
			List<String> commandList = new ArrayList<String>();
			commandList.add(cmdPath);
			commandList.add(srcPath);
			commandList.add(destPath);

			ProcessBuilder pb = new ProcessBuilder(commandList);
			process = pb.start();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					process.getErrorStream()));
			String line = reader.readLine();
			while (line != null) {
				line = reader.readLine();
			}

			process.destroy();
			return true;
		} catch (Exception e) {
			log.error("生成pdf失败", e);
			return false;
		} finally {
			if (process != null)
				process.destroy();
		}
	}

	public static void main(String[] args) {
		String pdfPath = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf";
		String srcPath = "E:\\abc\\1234.html";
		String destPath = "E:\\abc\\1234.pdf";
		String content = "123456sdfdfd";

		toPdf(content, pdfPath, srcPath, destPath, 860);
	}

}
